package com.lagou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lagou.feign.EmailService;
import com.lagou.mapper.CodeMapper;
import com.lagou.pojo.AuthCode;
import com.lagou.service.CodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName CodeServiceImpl
 * @Description
 * @Author playboy
 * @Date 2021/6/25 6:34 下午
 * @Version 1.0
 **/
@Service
@Transactional
public class CodeServiceImpl implements CodeService {
	private static Logger log = LoggerFactory.getLogger(CodeServiceImpl.class);

	@Autowired
	private CodeMapper codeMapper;

	@Autowired
	private EmailService emailService;

	/**
	 * 1.生成code
	 * 2.添加到数据库中
	 * 3.将code发送给指定邮件
	 *
	 * @param email
	 * @return
	 */
	@Override
	public boolean create(String email) {
		//生成随机数
		Integer code = ThreadLocalRandom.current().nextInt(100000, 999999);
		AuthCode authCode = new AuthCode();
		authCode.setEmail(email);
		authCode.setCode(code.toString());
		//当前时间
		Date now = new Date();
		//十分钟后的过期时间
		//Date expire = new Date(now.getTime() + 600000);
		//为了测试改为十秒钟的过期时间
		Date expire = new Date(now.getTime() + 20000);
		authCode.setCreatetime(now);
		authCode.setExpiretime(expire);

		codeMapper.insert(authCode);
		return emailService.email(email, code.toString());
	}

	/**
	 * 根据email查询出最后一条数据，并且将存储的code和传来的code比较
	 *
	 * @param email
	 * @param code
	 * @return
	 */
	@Override
	public Integer validate(String email, String code) {
		QueryWrapper<AuthCode> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("email", email);
		queryWrapper.orderByDesc("createtime");
		List<AuthCode> authCodes = codeMapper.selectList(queryWrapper);
		if (ObjectUtils.isEmpty(authCodes)) {
			return ValidateType.FAILD.getKey();
		}
		AuthCode authCode = authCodes.get(0);
		//先判断是否超时
		if (authCode.getExpiretime().compareTo(new Date()) < 0) {
			//已超时
			return ValidateType.TIMEOUT.getKey();
		}
		//判断是否code相同
		if (authCode.getCode().equals(code)) {
			return ValidateType.SUCCESS.getKey();
		}
		return ValidateType.FAILD.getKey();
	}

	static enum ValidateType {
		SUCCESS(0),
		FAILD(1),
		TIMEOUT(2);
		private final int key;

		private ValidateType(int key) {
			this.key = key;
		}

		public int getKey() {
			return this.key;
		}
	}

}
